import { useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Runtime } from 'wxt/browser';
import { getCurrentTab } from '@/lib/utils';
import { Card, CardContent } from '@/components/ui/card';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import readmeTxt from '@/readme.md?raw';
import MarkdownRenderer from '@/components/MarkdownRenderer';
import config, { MessageType, OpenOperationInstructionMessage } from '@/config';
import {
  operationInstructionName,
  operationInstructionStatus,
  Status,
} from '../operation-instruction.content';

let port: Runtime.Port | null = null;
async function getPort() {
  if (port) {
    return port;
  }
  const currentTab = await getCurrentTab();
  if (currentTab && currentTab.id && !currentTab.url?.startsWith('chrome://extensions/')) {
    port = await browser.tabs.connect(currentTab.id, { name: operationInstructionName });
    return port;
  }
  return null;
}

function App() {
  const [open, setOPen] = useState(false);

  useEffect(() => {
    async function sendMessage() {
      const port = await getPort();
      if (port) {
        port.postMessage({
          type: operationInstructionStatus,
          data: {
            status: open ? Status.open : Status.close,
          },
        });
      }
    }
    sendMessage();
  }, [open]);

  useEffect(() => {
    async function open() {
      const port = await getPort();
      if (port) {
        // 这里就不进行移除监听器了,因为重复执行 setOpen(true),没有副作用
        port.onMessage.addListener((message: OpenOperationInstructionMessage) => {
          if (message.type === MessageType.openOperationInstruction) {
            setOPen(true);
          }
        });
      }
    }
    open();
  }, []);

  return (
    <>
      <div className="pointer-events-auto">
        <Dialog open={open} onOpenChange={setOPen}>
          <DialogContent
            aria-describedby=""
            className="w-[80%] max-w-7xl h-[80vh] grid-rows-[auto_1fr]"
            style={{
              zIndex: config.dialogZIndex,
            }}
          >
            <DialogHeader>
              <DialogTitle className="text-card-foreground/80">使用说明</DialogTitle>
            </DialogHeader>
            <Card className="grow flex flex-col relative overflow-hidden">
              <ScrollArea className="border rounded-sm p-2 w-full h-full absolute">
                <div className="leading-loose">
                  <MarkdownRenderer content={readmeTxt}></MarkdownRenderer>
                </div>
                <ScrollBar orientation="horizontal"></ScrollBar>
              </ScrollArea>
            </Card>
          </DialogContent>
        </Dialog>
      </div>
    </>
  );
}

export default App;
